<?php

namespace Rexzy\Tool;

class Memcache {
    
    private $_m;
    
    public function __construct( $host, $port = 11211 ) {
        $this->_m = new \Memcache();
        $this->_m->addServer( $host, $port );
    }
    
    /**
     * 设置
     * 
     * @param string $key 键名 
     * @param mixed $var 设置值
     * @param int $expire 有效期
     */
    public function set( $key, $var, $expire = 9999999999 ) {
        $data = array(
            'value' => $var,
            'time' => time(),
            'expire' => time() + $expire,
        );
        $this->_m->set( $key, serialize($data), 0, $expire );
    }
    
    /**
     * 获取
     * 
     * @param string $key 键名
     * @param boolean $info 是否获取全部设置参数还是之获取值
     * @return mixed
     */
    public function get( $key, $info = false ) {
        $data = $this->_m->get( $key );
        if( $data ) {
            $data = unserialize($data);
        } else {
            return false;
        }
        if( $info ) {
            return $data;
        } else {
            return $data['value'];
        }
    }
    
    /**
     * 删除
     * 
     * @param string $key 键名
     */
    public function delete( $key ) {
        $this->_m->delete( $key );
    }
}
